package controller

import (
	"example.com/myproject/project/global"
	"example.com/myproject/project/models"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"regexp"
)

func Showflight(c *gin.Context) {
	var flights []models.Flight
	if err := global.Db.Find(&flights).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	for i := range flights {
		flights[i].SetFormattedDepartureTime() // 设置格式化时间
	}

	c.JSON(http.StatusOK, flights)
}

/*
获取首页活动的轮播图
*/
var (
	// \d是数字
	ImgName = `http://img0.(.*?)tub.jpg`
)

// 爬几张图片
func GetCarousel(c *gin.Context) {
	var imgurl []string = make([]string, 3)
	resp, err := http.Get("http://www.dili360.com/travel/sight/20212.htm")
	if err != nil {
		imgurl[0] = "https://dimg04.c-ctrip.com/images/0102c120008gmz1epE5D9_C_286_190.jpg"
		imgurl[1] = "https://dimg04.c-ctrip.com/images/0104h1200081xpesbDD88_C_286_190.jpg"
		imgurl[2] = "https://dimg04.c-ctrip.com/images/0104h1200080zn05m7E3F_C_286_190.jpg"
	}
	defer resp.Body.Close()
	pageBytes, err := ioutil.ReadAll(resp.Body)

	pageStr := string(pageBytes)

	re := regexp.MustCompile(ImgName)
	results := re.FindAllStringSubmatch(pageStr, -1)

	// 遍历结果
	for index, result := range results {
		if index >= 3 {
			break
		}
		if len(result[0]) < 10 {
			continue
		}
		imgurl[index] = result[0]
	}

	c.JSON(http.StatusOK, imgurl)
}

// 返回空闲的客机号
func GetFreeAircraft(c *gin.Context) {
	var airlist []int
	if err := global.Db.Table("aircrafts").
		Select("aircraft_id").
		Where("current_flight_number IS NULL").
		Scan(&airlist).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, airlist)
}

// 返回空闲的航班号
func GetFreeFlight(c *gin.Context) {
	var freeFlights []models.Flight

	// 使用子查询实现
	subQuery := global.Db.Table("aircrafts").
		Select("current_flight_number").
		Where("current_flight_number IS NOT NULL")

	if err := global.Db.Table("flights").
		Where("flight_number NOT IN (?)", subQuery).
		Find(&freeFlights).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	for i := range freeFlights {
		freeFlights[i].SetFormattedDepartureTime() // 设置格式化时间
	}

	c.JSON(http.StatusOK, freeFlights)

}
